package com.base.common.interceptor;

import com.base.common.util.BaseResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应拦截器
 */
@ControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true; // 拦截所有响应
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {

        if (body == null) {
            return BaseResponse.success(null);
        }

        if (body instanceof BaseResponse) {
            return body;
        }

        // String 类型单独处理，否则会报类型转换错误
        if (body instanceof String) {
            return "{\"code\":0,\"message\":\"success\",\"data\":\"" + body + "\"}";
        }

        return BaseResponse.success(body);
    }
}
